package com.youka.bussiness.common.utils;


import com.youka.bussiness.common.base.BaseException;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/*********************************
 * 文件名称：MD5Secret.java
 * 开发人员：liujinliang
 * 开发时间：2017/11/9 17:00
 *********************************/

public class MD5Secret {


    /**
     * 通过加盐的方式对密码进行MD5加密
     *
     * @param origin
     * @param random
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public static String cipherMD5(String origin, String random) {
        try {
            StringBuffer md = new StringBuffer();
            md.append(origin).append(random);
            return MD5EncodeToHex(md.toString());
        } catch (Exception e) {
            throw new BaseException("MD-100005", "加密发生异常");
        }
    }

    /**
     * 对密码进行MD5加密
     *
     * @param origin
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public static String cipherMD5(String origin) {
        try {
            return MD5EncodeToHex(origin);
        } catch (Exception e) {
            throw new BaseException("MD-100006", "加密发生异常");
        }
    }

    /**
     * 加密解密算法 执行一次加密，两次解密
     */
    public static String convertMD5(String inStr) {

        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;

    }


    /**
     * MD5加密字符串，返回加密后的16进制字符串
     *
     * @param origin
     * @return
     */
    private static String MD5EncodeToHex(String origin) {
        try {
            return ByteUtil.getHexString(MD5Encode(origin.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            throw new BaseException("MD-100007", "不支持的编码方式");
        } catch (NoSuchAlgorithmException e) {
            throw new BaseException("MD-100008", "没有匹配的算法");
        }
    }

    /**
     * MD5加密字节数组，返回加密后的字节数组
     *
     * @param bytes
     * @return
     */
    private static byte[] MD5Encode(byte[] bytes) throws NoSuchAlgorithmException {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            return md.digest(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw e;
        }
    }

}